package com.wish.wishhouse_foreclosure.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wish.wishhouse_foreclosure.entity.SysUser;
import com.wish.wishhouse_foreclosure.entity.TSfContract;
import com.wish.wishhouse_foreclosure.entity.TbHouseInfo;
import com.wish.wishhouse_foreclosure.enums.*;
import com.wish.wishhouse_foreclosure.service.ISysUserService;
import com.wish.wishhouse_foreclosure.service.ITSfContractService;
import com.wish.wishhouse_foreclosure.service.ITbHouseInfoService;
import dto.houseForeclosureDto.*;
import dto.response.ResponseSearchSfsDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import dto.houseResourceDto.TSfContractDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import vo.ResultEntity;

import dto.houseForeclosureDto.RequestDetailSfContractDto;
import dto.houseForeclosureDto.RequestTerminalSfContractDto;
import dto.houseForeclosureDto.ResponseDetailSfContractDto;
import dto.houseForeclosureDto.TsfContractDto;
import dto.houseForeclosureDto.contractCloseAdd.ItemInfo;
import dto.houseForeclosureDto.contractCloseAdd.SaveSfTerminationForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import utils.PayMentPlanGenerator;
import utils.PhoneFormatCheckUtils;
import utils.RegularCheckUtils;
import vo.ResultEntity;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangshuxin
 * @since 2021-03-31
 */
@RestController
@RequestMapping("/tSfContract")
@Slf4j
public class TSfContractController {

    @Autowired
    private ITSfContractService itSfContractService;
    @Autowired
    private ITbHouseInfoService iTbHouseInfoService;

    @RequestMapping("/paymentPayEnum")
    public PaymentPayEnum[] PaymentPayEnum(){
        PaymentPayEnum[] values = PaymentPayEnum.values();
        return values;
    }

    @RequestMapping("/tenantManageEnum")
    public TenantManageEnum[] TenantManageEnum(){
        TenantManageEnum[] values = TenantManageEnum.values();
        return values;
    }
    @RequestMapping("/leaseType")
    public LeaseType[] LeaseType(){
        LeaseType[] values = LeaseType.values();
        return values;
    }
    @RequestMapping("/houseAllTypeEnum")
    public HouseAllTypeEnum[] houseAllTypeEnum(){
        HouseAllTypeEnum[] values = HouseAllTypeEnum.values();
        return values;
    }
    @RequestMapping("/certificateType")
    public CertificateType[] CertificateType(){
        CertificateType[] values = CertificateType.values();
        return values;
    }
    @RequestMapping("/selects")
    public ResultEntity selects(TSfContractDto tSfContractDto){
        PageHelper.startPage(tSfContractDto.getPageNum(),tSfContractDto.getPageSize());
        PageInfo<TSfContract> info =itSfContractService.selects(tSfContractDto);
        return ResultEntity.ok("200",info);
    }



    @RequestMapping("/searchContractList")
    public ResultEntity searchContractList(TsfContractDto tsfContractDto){
        PageHelper.startPage(tsfContractDto.getPageNum(),tsfContractDto.getPageSize());
        List<TSfContract> tSfContractList = itSfContractService.selectPageVo(tsfContractDto);
        PageInfo<TSfContract> pageInfo = new PageInfo<>(tSfContractList);
        return ResultEntity.ok(pageInfo);
    }

    /**
     * 根据合同租约信息生成相应账期的付款计划信息
     *
     * @param
     * @return
     * @throws ParseException
     */
    @RequestMapping("/generatePayMentPlan")
    private Map generatePayMentPlan(@RequestBody SaveSfContractForm saveSfContractForm) throws ParseException {
        // 计算生成各账期付款计划
        CalculateFkPlanForm dataPlan = new CalculateFkPlanForm();
        BeanUtils.copyProperties(saveSfContractForm, dataPlan);
        dataPlan.setMonthRent(new BigDecimal(saveSfContractForm.getMonthRent()));// 收房月租金
        dataPlan.setDepositMoney(new BigDecimal(saveSfContractForm.getDepositMoney()));// 房产押金
        List<CwPaymentPlanDto> payMentPlanList = PayMentPlanGenerator.generatePayMentPlan(dataPlan);
        HashMap<String, Object> map = new HashMap<>();
        map.put("payMentPlanList", payMentPlanList);
        BigDecimal totalDeposit = new BigDecimal(saveSfContractForm.getDepositMoney())
                .multiply(new BigDecimal(saveSfContractForm.getDepositType()));
        if (BigDecimal.ZERO.equals(totalDeposit)) {
            // 无押金
            map.put("hasDeposit", 0);
        } else {
            // 有押金
            map.put("hasDeposit", 1);
        }
        if (null != saveSfContractForm.getLastContractId()) {
            map.put("isXuYue", 1);
        } else {
            map.put("isXuYue", 0);
        }
        // 合同总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (CwPaymentPlanDto cwPaymentPlanDto : payMentPlanList) {
            totalAmount = totalAmount.add(cwPaymentPlanDto.getPaymentAmount());
        }
        map.put("totalAmount", totalAmount);
        map.put("totalDeposit", totalDeposit);
        map.put("preCycleChange", 0);

        return map;
    }

    /**
     *
     * @Description: 保存收房合同
     * @param @param
     *            saveSfContractForm
     * @param @param
     *            bindingResult
     * @param @return
     *            参数
     * @return 返回值说明
     * @throws Exception
     */

    @RequestMapping("/saveSfContract")
    private ResultEntity saveSfContract(@RequestBody  SaveSfContractForm saveSfContractForm)
            throws Exception {

        RequestDetailSfContractSaveDto requestDetailSfContractSaveDto = new RequestDetailSfContractSaveDto();
        BeanUtils.copyProperties(saveSfContractForm, requestDetailSfContractSaveDto);
        requestDetailSfContractSaveDto.setDepositMoney(new BigDecimal(saveSfContractForm.getDepositMoney()));
        requestDetailSfContractSaveDto.setMonthRent(new BigDecimal(saveSfContractForm.getMonthRent()));
        requestDetailSfContractSaveDto.setHouseName(saveSfContractForm.getHouseInfo());
        requestDetailSfContractSaveDto.setLeaseStartTime(saveSfContractForm.getStartDate());
        requestDetailSfContractSaveDto.setLeaseEndTime(saveSfContractForm.getEndDate());
        itSfContractService.saveSfContract(requestDetailSfContractSaveDto);
        return ResultEntity.ok();
    }

    /**
     * ***********************************************************************************************************
     */
    /**
     * 弹出收房合同查询 List列表带分页 续约使用
     */
    @RequestMapping("/searchSfContractList_xy")
    public ResultEntity searchSfContractListXy(@RequestBody RequestSearchSfsDto requestSearchSfsDto) {
        PageHelper.startPage(requestSearchSfsDto.getPageNum(), requestSearchSfsDto.getPageSize());
        List<ResponseSearchSfsDto> responseSearchSfsDtos = itSfContractService.listSfByXy(requestSearchSfsDto);
        PageInfo<ResponseSearchSfsDto> info = new PageInfo<>(responseSearchSfsDtos);
        return ResultEntity.ok(info);
    }
    @RequestMapping("/searchSfAll")
    public ResultEntity searchSfAll( TsfContractDto tsfContractDto)
            throws ParseException {


        PageHelper.startPage(tsfContractDto.getPageNum(),tsfContractDto.getPageSize());
        List<TSfContract> tSfContractList = itSfContractService.searchSfAllNotDissolution(tsfContractDto);
        PageInfo<TSfContract> pageInfo = new PageInfo<>(tSfContractList);

        return ResultEntity.ok(pageInfo);
    }



    @RequestMapping("/searchSfAllById")
    public ResultEntity searchSfAllById(Long sfContractId) throws ParseException {

        RequestDetailSfContractDto requestDetailSfContractDto = new RequestDetailSfContractDto();
        ResponseDetailSfContractDto detailSfContract = null;
        if (null != sfContractId) {

            requestDetailSfContractDto.setSfContractId(sfContractId);

            detailSfContract = itSfContractService.detailSfContractB(requestDetailSfContractDto);
            return ResultEntity.ok(detailSfContract);
        }

        return ResultEntity.ok(detailSfContract);
    }


//保存合同  保存合同  保存合同  保存合同  保存合同
//    @ResponseBody

    @RequestMapping("/saveSfTermination")
    private void saveSfTermination( @RequestBody SaveSfTerminationForm saveSfTerminationFrom) throws Exception {
//        System.out.println("88887776"+requestTerminalSfContractDto);
//        itSfContractService.terminalSfContract(requestTerminalSfContractDto);


//        //	动态增加1  动态增加1 动态增加1
//        private String[] itemType1;
//
//        private BigDecimal[] amount1;
//
//        private String[] detailRemark1;


        String s1[] = new String[2]; /*开辟了一个长度为3的数组*/
        s1[0] = "1"; // 第一个元素
        s1[1] ="1"; // 第二个元素

        BigDecimal[] b1 = new BigDecimal[2];

        b1[0] = BigDecimal.valueOf(1); // 第一个元素
        b1[1] = BigDecimal.valueOf(1); // 第二个元素


        String d1[] = new String[2]; /*开辟了一个长度为3的数组*/
        d1[0] = "40"; // 第一个元素
        d1[1] ="40"; // 第二个元素


        String s2[] = new String[2]; /*开辟了一个长度为3的数组*/
        s2[0] = "1"; // 第一个元素
        s2[1] ="1"; // 第二个元素

        BigDecimal[] b2 = new BigDecimal[2];

        b2[0] = BigDecimal.valueOf(1); // 第一个元素
        b2[1] = BigDecimal.valueOf(1); // 第二个元素


        String d2[] = new String[2]; /*开辟了一个长度为3的数组*/
        d2[0] = "40"; // 第一个元素
        d2[1] ="40"; // 第二个元素


//        itSfContractService.terminalSfContract(saveSfTerminationFrom);

        saveSfTerminationFrom.setItemType1(s1);
        saveSfTerminationFrom.setAmount1(b1);
        saveSfTerminationFrom.setDetailRemark1(d1);


        saveSfTerminationFrom.setItemType2(s2);
        saveSfTerminationFrom.setAmount2(b2);
        saveSfTerminationFrom.setDetailRemark2(d2);

        String json = this.transformationJson(saveSfTerminationFrom);

        RequestTerminalSfContractDto terminalSfContractDto = new RequestTerminalSfContractDto();
        BeanUtils.copyProperties(saveSfTerminationFrom, terminalSfContractDto);

        terminalSfContractDto.setStatementDetailJson(json);

            this.itSfContractService.terminalSfContract(terminalSfContractDto);
    }


    /**
     *
     * @Description: 数组转成json串
     * @param saveSfTerminationFrom
     * @return String
     */
    public String transformationJson(SaveSfTerminationForm saveSfTerminationFrom) {

        List<ItemInfo> infos = new ArrayList<ItemInfo>();
        String[] itemType1 = saveSfTerminationFrom.getItemType1();
        BigDecimal[] amount1 = saveSfTerminationFrom.getAmount1();
        String[] detailRemark1 = saveSfTerminationFrom.getDetailRemark1();
        /**
         * 遍历应退信息
         */
        for (int i = 1; i < itemType1.length; i++) {
            ItemInfo item = new ItemInfo();
            item.setItemType(itemType1[i]);
            item.setAmount(amount1[i]);
            item.setDetailRemark(detailRemark1[i]);
            item.setDealType("1");
            infos.add(item);
        }

        String[] itemType2 = saveSfTerminationFrom.getItemType2();
        BigDecimal[] amount2 = saveSfTerminationFrom.getAmount2();
        String[] detailRemark2 = saveSfTerminationFrom.getDetailRemark2();
        /**
         * 遍历应收信息
         *
         */
        for (int i = 0; i < itemType2.length; i++) {
            ItemInfo item = new ItemInfo();
            item.setItemType(itemType2[i]);
            item.setAmount(amount2[i]);
            item.setDetailRemark(detailRemark2[i]);
            item.setDealType("2");
            infos.add(item);
        }

        return JSON.toJSON(infos).toString();
    }

}

